﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadLearn
{
    internal static class ParallelDemo
    {
        public static Int64 DirectoryBytes(String path,String searchPattern,SearchOption searchOption)
        {
            var files = Directory.EnumerateFiles(path, searchPattern, searchOption);
            Int64 masterTotal = 0;
            ParallelLoopResult result = Parallel.ForEach<String, Int64>(files,
                () =>
                {
                    return 0;
                },
                (file, loopState, index, taskLocalTotal) =>
                {
                    Int64 fileLength = 0;
                    FileStream fs = null;
                    try
                    {
                        fs = File.OpenRead(file);
                        fileLength = fs.Length;
                    }
                    catch (IOException)
                    { }
                    finally
                    {
                        if (fs != null) fs.Dispose();
                    }
                    return taskLocalTotal + fileLength;
                },
                taskLocalTotal =>
                {
                    Interlocked.Add(ref masterTotal, taskLocalTotal);
                });
            return masterTotal;
        }

        public static void DisplayResult(String path, String searchPattern, SearchOption searchOption)
        {
            Console.WriteLine("Result=>" + ParallelDemo.DirectoryBytes(path, searchPattern, searchOption));
            Console.Read();
        }

    }
}
